package services

import (
	"errors"

	"gorm.io/gorm"

	"ppp/internal/config"
	"ppp/internal/models"
)

// NewsService 新闻服务接口
type NewsService interface {
	CreateNews(req *models.CreateNewsRequest) (*models.News, error)
	GetNewsByID(id uint) (*models.News, error)
	UpdateNews(id uint, req *models.UpdateNewsRequest) (*models.News, error)
	DeleteNews(id uint) error
	ListNews() ([]models.News, error)
}

// newsService 新闻服务实现
type newsService struct {
	db *gorm.DB
}

// NewNewsService 创建新闻服务实例
func NewNewsService() NewsService {
	return &newsService{
		db: config.GetDB(),
	}
}

// CreateNews 创建新闻
func (s *newsService) CreateNews(req *models.CreateNewsRequest) (*models.News, error) {
	news := &models.News{
		Title:   req.Title,
		Content: req.Content,
		Author:  req.Author,
	}

	result := s.db.Create(news)
	if result.Error != nil {
		return nil, result.Error
	}

	return news, nil
}

// GetNewsByID 根据ID获取新闻
func (s *newsService) GetNewsByID(id uint) (*models.News, error) {
	var news models.News
	result := s.db.First(&news, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, errors.New("新闻不存在")
		}
		return nil, result.Error
	}
	return &news, nil
}

// UpdateNews 更新新闻
func (s *newsService) UpdateNews(id uint, req *models.UpdateNewsRequest) (*models.News, error) {
	// 检查新闻是否存在
	news, err := s.GetNewsByID(id)
	if err != nil {
		return nil, err
	}

	// 更新新闻信息
	news.Title = req.Title
	news.Content = req.Content
	news.Author = req.Author

	result := s.db.Save(news)
	if result.Error != nil {
		return nil, result.Error
	}

	return news, nil
}

// DeleteNews 删除新闻
func (s *newsService) DeleteNews(id uint) error {
	// 检查新闻是否存在
	_, err := s.GetNewsByID(id)
	if err != nil {
		return err
	}

	result := s.db.Delete(&models.News{}, id)
	if result.Error != nil {
		return result.Error
	}

	return nil
}

// ListNews 获取新闻列表
func (s *newsService) ListNews() ([]models.News, error) {
	var news []models.News
	result := s.db.Find(&news)
	if result.Error != nil {
		return nil, result.Error
	}

	return news, nil
}